package com.lbjhan.rpc.consumer.processor;

import com.lbjhan.rpc.consumer.anno.RpcAutowire;
import com.lbjhan.rpc.consumer.proxy.RpcClientProxy;
import com.lbjhan.rpc.consumer.client.RpcNettyClient;
import com.lbjhan.rpc.consumer.proxy.RpcClientResponseProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class ProxyBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    RpcClientResponseProxy rpcClientResponseProxy;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 在bean实例化之后，将bean实例中标有@RpcAutowire注解的属性注入
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        for(Field field : beanClass.getDeclaredFields()){
            if(field.getAnnotation(RpcAutowire.class)!=null){
                Object proxy = rpcClientResponseProxy.createProxy(field.getType());
                field.setAccessible(true);
                try {
                    field.set(bean, proxy);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
}
